package com.mths.server.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.mths.client.util.ListItem;
import com.mths.server.entity.DocumentType;

@Repository("documentTypeDAO")
@Transactional
public class DocumentTypeDAOImpl extends AbstractDAOImpl<String, DocumentType> implements DocumentTypeDAO {

	@Override
	public List<ListItem> loadDocumentClassCombo() throws Exception {
		String sqlStr = "select t.objid, t.name from DocumentType t where t.parentDocument is null ";
		Query query = getEntityManager().createQuery(sqlStr);

		List<Object[]> result = (List<Object[]>) query.getResultList();
		List<ListItem> docClassList = new ArrayList<ListItem>();
		if (result != null) {
			for (Object[] stringArr : result) {
				String objid = (String) stringArr[0];
				String name = (String) stringArr[1];
				docClassList.add(new ListItem(objid, name));
			}
		}
		return docClassList;
	}

	@Override
	public List<DocumentType> loadAllDocClass() {
		String sqlStr = "select t from DocumentType t where t.parentDocument is null";
		Query query = getEntityManager().createQuery(sqlStr);
		return query.getResultList();
	}

	@Override
	public List<DocumentType> loadDocTypeListByParentOid(String parentOid) {
		String sqlStr = "select t from DocumentType t where t.parentDocument.objid = :parentOid";
		Query query = getEntityManager().createQuery(sqlStr);
		query.setParameter("parentOid", parentOid);

		return query.getResultList();
	}

	@Override
	public List<ListItem> loadDocTypeComboByParentOid(String parentOid) {
		String sqlStr = "select t.objid, t.name from DocumentType t where t.parentDocument.objid = :parentOid";
		Query query = getEntityManager().createQuery(sqlStr);
		query.setParameter("parentOid", parentOid);

		List<Object[]> result = (List<Object[]>) query.getResultList();
		List<ListItem> docTypeList = new ArrayList<ListItem>();
		if (result != null) {
			for (Object[] stringArr : result) {
				String objid = (String) stringArr[0];
				String name = (String) stringArr[1];
				docTypeList.add(new ListItem(objid, name));
			}
		}
		return docTypeList;
	}

	@Override
	public String findDocumentTypeNameByOid(String documentTypeOid) throws Exception {

		if (StringUtils.isEmpty(documentTypeOid))
			return null;

		DocumentType documentType = findByOid(documentTypeOid);
		if (documentType == null)
			throw new Exception("Document Type bulunamadı");
		return documentType.getName();
	}

}
